package com.holike.crm.activity.main;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Process;
import android.view.MotionEvent;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;

import com.galloped.tablayout.TabLayout;
import com.galloped.tablayout.tab.Tab;
import com.galloped.tablayout.tab.TabEntity;
import com.holike.crm.R;
import com.holike.crm.activity.customer.CustomerDetailV2Activity;
import com.holike.crm.activity.login.LoginActivity;
import com.holike.crm.base.BaseActivity;
import com.holike.crm.bean.UpdateBean;
import com.holike.crm.dialog.UpdateAppDialog;
import com.holike.crm.enumeration.CustomerValue;
import com.holike.crm.fragment.main.CustomerV2Fragment;
import com.holike.crm.fragment.main.HomepageV2Fragment;
import com.holike.crm.fragment.main.MineFragment;
import com.holike.crm.fragment.main.OrderV2Fragment;
import com.holike.crm.fragment.main.ReportV3Fragment;
import com.holike.crm.helper.FragmentSwitcher;
import com.holike.crm.presenter.activity.MainPresenter;
import com.holike.crm.util.AppUtils;
import com.holike.crm.util.KeyBoardUtil;
import com.holike.crm.view.activity.MainView;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * 主页
 */

public class MainActivity extends BaseActivity<MainPresenter, MainView> implements MainView {
    @BindView(R.id.tab_main)
    TabLayout mTabLayout;

    private long mExitTime;
    private Handler mHandler = new Handler(Looper.getMainLooper());

    private FragmentSwitcher mFragmentSwitcher;
    private MainHelper mHelper;

    private UpdateAppDialog mUpdateAppDialog;  //更新提示框
    private static final int REQUEST_CODE_APP_INSTALL = 2020;

    @Override
    protected MainPresenter attachPresenter() {
        return new MainPresenter();
    }

    @Override
    protected int getLayoutResourceId() {
        return R.layout.activity_main;
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        setStatusBarColor(R.color.textColor14);
        if (getIntent().getBooleanExtra("logout", false)) {//退出登录
            startActivity(LoginActivity.class);
            finish();
            return;
        }
        MainPresenter.setAlias();
        mFragmentSwitcher = FragmentSwitcher.obtain(R.id.fl_main_fragment, mFragmentManager);
        setupTab();
        initFragments();
        obtainState(savedInstanceState);
        mHelper = new MainHelper(this, mHandler);
        checkVersion();
        getGlobalData();
    }

    private void setupTab() {
        List<Tab> tabList = new ArrayList<>();
        tabList.add(new TabEntity(getString(R.string.tab_home), ContextCompat.getDrawable(this, R.drawable.ic_home_sel), ContextCompat.getDrawable(this, R.drawable.ic_home_nor)));
        tabList.add(new TabEntity(getString(R.string.tab_customer), ContextCompat.getDrawable(this, R.drawable.ic_customer_sel), ContextCompat.getDrawable(this, R.drawable.ic_customer_nor)));
        tabList.add(new TabEntity(getString(R.string.tab_order), ContextCompat.getDrawable(this, R.drawable.ic_order_sel), ContextCompat.getDrawable(this, R.drawable.ic_order_nor)));
        tabList.add(new TabEntity(getString(R.string.tab_report), ContextCompat.getDrawable(this, R.drawable.ic_analysis_sel), ContextCompat.getDrawable(this, R.drawable.ic_analysis_nor)));
        tabList.add(new TabEntity(getString(R.string.tab_mine), ContextCompat.getDrawable(this, R.drawable.ic_mine_sel), ContextCompat.getDrawable(this, R.drawable.ic_mine_nor)));
        mTabLayout.setupTab(tabList);
        mTabLayout.setOnTabSelectListener(new TabLayout.OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                mFragmentSwitcher.setCurrentTab(position);
            }

            @Override
            public void onTabReselect(int position) {
                statistics(position);
            }
        });
    }

    private void initFragments() {
        List<Fragment> fragments = new ArrayList<>();
        fragments.add(new HomepageV2Fragment());
        fragments.add(new CustomerV2Fragment());
        fragments.add(new OrderV2Fragment());
        fragments.add(new ReportV3Fragment());
        fragments.add(new MineFragment());
        mFragmentSwitcher.setup(fragments, new String[]{"tag-home", "tag-customer", "tag_order", "tag-analysis", "tag-mine"});
        mFragmentSwitcher.setOnFragmentChangeListener(this::statistics);
    }

    private void statistics(int position) {
        switch (position) {
            case 0:
                MobclickAgent.onEvent(this, "homepage");
                break;
            case 1:
                MobclickAgent.onEvent(this, "customer");
                break;
            case 2:
                MobclickAgent.onEvent(this, "order");
                break;
            case 3:
                MobclickAgent.onEvent(this, "analyze");
                break;
            case 4:
                MobclickAgent.onEvent(this, "my_mine");
                break;
        }
    }

    private void obtainState(Bundle savedInstanceState) {
        if (savedInstanceState != null) {
            int currentTab = savedInstanceState.getInt("currentTab", 0);
            mFragmentSwitcher.setCurrentTab(currentTab);
        }
    }

    private void checkVersion() {
        mPresenter.checkVersion();
    }

    @Override
    public void onBackPressed() {
        if ((System.currentTimeMillis() - mExitTime) > 2000) {
            showShortToast(R.string.tips_exit);
            mExitTime = System.currentTimeMillis();
        } else {
            finish();
            Process.killProcess(Process.myPid());
//            SophixManager.getInstance().killProcessSafely();
        }
    }

    /**
     * 发现新版本
     */
    @Override
    public void onGetVersion(UpdateBean updateBean, boolean hasNewVersion) {
        if (hasNewVersion) { //有新版本，则弹出更新提示窗
            showUpdateAppDialog(this, updateBean);
        }
    }

    /*请求失败，则间隔5s再次请求*/
    @Override
    public void onFailure() {
        mHandler.postDelayed(this::checkVersion, 5000);
    }

    /**
     * 版本更新弹窗
     */
    public void showUpdateAppDialog(final Context context, final UpdateBean updateBean) {
        if (mUpdateAppDialog == null) {
            mUpdateAppDialog = new UpdateAppDialog(context, updateBean, () -> AppUtils.startUnknownAppSourceSetting(MainActivity.this, REQUEST_CODE_APP_INSTALL));
        }
        if (!mUpdateAppDialog.isShowing())
            mUpdateAppDialog.show();
    }

    /*获取全局数据*/
    private void getGlobalData() {
        getApp().getSystemCodeItems();
        getApp().getUserInfo();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        if (mHelper != null) {
            mHelper.onRestart();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_APP_INSTALL && AppUtils.canInstallApk() && mUpdateAppDialog != null) {
            mUpdateAppDialog.installApk(AppUtils.getTargetApkPath());
        } else {
            if ((resultCode == CustomerValue.RESULT_CODE_ACTIVATION ||
                    resultCode == CustomerValue.RESULT_CODE_HIGH_SEAS) && data != null) {
                String personalId = data.getStringExtra(CustomerValue.PERSONAL_ID);
                String houseId = data.getStringExtra(CustomerValue.HOUSE_ID);
                CustomerDetailV2Activity.open(this, personalId, houseId, false);
            }
        }
    }

    /*客户搜索，订单搜索，当触摸搜索框以外地方，隐藏软键盘*/
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (KeyBoardUtil.isShouldHideInput(v, ev)) {
                v.clearFocus();
                KeyBoardUtil.hideKeyboard(v);
            }
            return super.dispatchTouchEvent(ev);
        }
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);
    }

    @Override
    protected void onSaveInstanceState(@NonNull Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt("currentTab", mFragmentSwitcher.getCurrentTab());  //状态发生改变 保存当前切换tab位置
    }

    @Override
    protected void onDestroy() {
        if (mHelper != null) {
            mHelper.deDeath();
        }
        if (mUpdateAppDialog != null) {
            mUpdateAppDialog.dismiss();
        }
        mHandler.removeCallbacksAndMessages(null);
        super.onDestroy();
    }
}
